import { getProfileAPI, loginAPI } from '@/api/user'
import { asyncRoutes, resetRouter } from '@/router'
import { getToken, removeToken, setToken, TOKEN_KEY } from '@/utils/auth'
export default {
  namespaced: true,
  state: () => {
    return {
      token: getToken() || '',
      profile: {},
      menuList: [...asyncRoutes]
    }
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    clearUserInfo(state) {
      // 清除Token
      state.token = ''
      state.profile = {}
      removeToken(TOKEN_KEY)
    },
    logout() {
      this.$store.commit('clearUser')
      this.$router.push('/login')
    },
    setProfile(state, profile) {
      state.profile = profile
    },
    setMenuList(state, filterRoutes) {
      state.menuList = [...state.menuList, ...filterRoutes]
    },
    resetMenu(state) {
      // 重置左侧菜单
      state.menuList = asyncRoutes
      // 重置路由系统
      resetRouter()
    }
  },
  actions: {
    async doLogin(ctx, { username, password }) {
      console.log('444')
      const res = await loginAPI({ username, password })
      console.log('loginAPI--res', res)
      ctx.commit('setToken', res.data.token)
    },
    async getProfile(ctx) {
      const res = await getProfileAPI()
      ctx.commit('setProfile', res.data)
      console.log('getProfile', res.data)
      return res.data.permissions
    }
  }
}
